<template>
  <div class="max-w-6xl mx-auto p-6 min-h-screen bg-gradient-to-br from-slate-50 to-emerald-50">
    <!-- 页面标题 -->
    <div class="text-center mb-8 p-8 bg-white rounded-2xl shadow-lg">
      <h2 class="flex items-center justify-center gap-3 text-3xl font-semibold text-gray-800 mb-2">
        <n-icon class="text-4xl text-emerald-500" :component="SearchIcon" />
        政审外调编辑
      </h2>
      <p class="text-gray-600">请完善政审外调记录</p>
    </div>

    <!-- 提示信息模块 -->
    <div class="mb-6 bg-gradient-to-r from-emerald-50 to-green-50 border border-emerald-200 rounded-2xl p-6 shadow-sm">
      <div class="flex items-center gap-3 mb-4">
        <n-icon class="text-2xl text-emerald-600" :component="InfoIcon" />
        <h3 class="text-lg font-semibold text-emerald-800">重要提示信息</h3>
      </div>
      <div class="space-y-2">
        <div v-for="(tip, index) in tipMessages" :key="index" class="flex items-start gap-3 text-sm text-emerald-700">
          <div class="flex-shrink-0 w-1.5 h-1.5 bg-emerald-500 rounded-full mt-2"></div>
          <span>{{ tip }}</span>
        </div>
      </div>
    </div>

    <!-- 政审外调记录卡片 -->
    <n-card class="mb-6 rounded-2xl border-0 shadow-lg bg-white overflow-hidden" title="" :bordered="false">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3 py-2">
            <n-icon class="text-xl text-emerald-500" :component="SearchIcon" />
            <span class="text-lg font-semibold text-gray-800">政审外调记录</span>
          </div>
          <n-button 
            type="primary" 
            @click="addInvestigation"
            class="rounded-lg"
            ghost
          >
            <template #icon>
              <n-icon :component="PlusIcon" />
            </template>
            新增外调记录
          </n-button>
        </div>
      </template>

      <div class="mb-3">
        <n-empty 
          v-if="!externalInvestigations || externalInvestigations.length === 0"
          description="暂无外调记录"
          class="py-8 text-slate-500"
        >
          <template #icon>
            <n-icon :component="SearchIcon" class="text-3xl text-slate-400" />
          </template>
        </n-empty>
        
        <div v-for="(investigation, index) in externalInvestigations" :key="investigation.tempId || investigation.id || index" 
             class="bg-emerald-50 border border-emerald-200 rounded-xl p-4 mb-3 transition-all duration-300 hover:shadow-md hover:-translate-y-0.5">
          <div class="flex justify-between items-center mb-3">
            <div class="flex items-center gap-3">
              <span class="flex items-center justify-center w-6 h-6 bg-emerald-500 text-white rounded-full text-xs font-semibold">{{ index + 1 }}</span>
              <span v-if="investigation.isNew" class="px-2 py-1 bg-green-100 text-green-600 text-xs rounded-full">新增</span>
            </div>
            <div class="flex gap-2">
              <n-button 
                type="primary" 
                @click="saveInvestigation(investigation, index)"
                :loading="investigationSaveLoading[index]"
                :disabled="!investigationChanged[index]"
                class="rounded-lg"
                size="small"
              >
                <template #icon>
                  <n-icon :component="SaveIcon" />
                </template>
                保存
              </n-button>
              <n-button 
                text 
                type="error" 
                @click="deleteInvestigation(investigation, index)"
                :loading="investigationDeleteLoading[index]"
                class="text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-all duration-300"
                size="small"
              >
                <template #icon>
                  <n-icon :component="DeleteIcon" />
                </template>
                {{ investigation.isNew ? '取消' : '删除' }}
              </n-button>
            </div>
          </div>
          
          <n-grid :cols="12" :x-gap="12" :y-gap="6">
            <n-gi :span="4">
              <n-form-item label="被调查人姓名" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="investigation.personName" 
                  placeholder="如：王某某"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="与发展对象的关系" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-input 
                  v-model:value="investigation.relationshipDesc" 
                  placeholder="如：父亲"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
            <n-gi :span="4">
              <n-form-item label="落款日期" label-placement="top" :label-style="{ fontSize: '13px' }">
                <n-date-picker 
                  v-model:formatted-value="investigation.signatureDate" 
                  value-format="yyyy-MM-dd" 
                  type="date" 
                  placeholder="选择落款日期"
                  style="width: 100%"
                  class="rounded-lg"
                  size="small"
                />
              </n-form-item>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import {
  NForm, NFormItem, NGrid, NGi, NInput, 
  NDatePicker, NButton, NCard, NIcon, NEmpty
} from 'naive-ui'
import { 
  SearchOutline as SearchIcon,
  InformationCircle as InfoIcon,
  Add as PlusIcon,
  TrashOutline as DeleteIcon,
  Save as SaveIcon
} from '@vicons/ionicons5'
import { cloneDeep } from 'lodash-es';

const props = defineProps({
  member: {
    type: Object,
    required: true
  }
})

const emit = defineEmits([
  'save-external-investigation',
  'delete-external-investigation'
])

// 安全处理日期字段的函数
const safeDateValue = (dateStr) => {
  if (!dateStr || dateStr === '' || dateStr === 'null' || dateStr === 'undefined') {
    return null
  }
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) {
    return null
  }
  return dateStr
}

// 列表数据
const externalInvestigations = ref([])

// 原始数据副本，用于比较变化
const originalExternalInvestigations = ref([])

// 变化状态
const investigationChanged = ref({})

// 加载状态
const investigationSaveLoading = ref({})
const investigationDeleteLoading = ref({})

// 提示信息配置
const tipMessages = ref([
  '政审外调是对发展对象的社会关系和背景进行调查',
  '每条记录应包含被调查人姓名、关系描述和落款日期',
  '被调查人通常是与发展对象有密切关系的亲友、同事等',
  '关系描述应准确清晰，如"父亲"、"同事"、"朋友"等',
  '落款日期应为实际调查完成的日期'
])

// 生成唯一临时ID
const generateTempId = () => {
  return `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 深度比较对象是否相等
const isEqual = (obj1, obj2) => {
  return JSON.stringify(obj1) === JSON.stringify(obj2)
}

// 初始化数据
const initData = () => {
  if (props.member) {
    // 初始化外调记录数据并处理日期字段
    const investigationsData = (props.member.externalInvestigations || []).map(investigation => ({
      ...investigation,
      signatureDate: safeDateValue(investigation.signatureDate)
    }))
    
    externalInvestigations.value = cloneDeep(investigationsData)
    
    // 保存原始数据
    originalExternalInvestigations.value = cloneDeep(investigationsData)
  }
}

// 监听外调记录列表变化
watch(externalInvestigations, (newList) => {
  newList.forEach((item, index) => {
    const original = originalExternalInvestigations.value.find(orig => orig.id === item.id)
    if (item.isNew || !original) {
      // 新增的记录，检查是否有内容变化
      const emptyItem = {
        personName: '',
        relationshipDesc: '',
        signatureDate: null
      }
      investigationChanged.value[index] = !isEqual({
        personName: item.personName,
        relationshipDesc: item.relationshipDesc,
        signatureDate: item.signatureDate
      }, emptyItem)
    } else {
      // 现有记录，与原始数据比较
      investigationChanged.value[index] = !isEqual({
        personName: item.personName,
        relationshipDesc: item.relationshipDesc,
        signatureDate: item.signatureDate
      }, {
        personName: original.personName,
        relationshipDesc: original.relationshipDesc,
        signatureDate: original.signatureDate
      })
    }
  })
}, { deep: true })

onMounted(() => {
  initData()
})

watch(() => props.member, () => {
  initData()
}, { deep: true })

// =============== 外调记录操作 ===============
const addInvestigation = () => {
  const tempId = generateTempId()
  const newInvestigation = {
    tempId,
    isNew: true,
    personName: '',
    relationshipDesc: '',
    signatureDate: null
  }
  externalInvestigations.value.unshift(newInvestigation)
}

const saveInvestigation = async (investigation, index) => {
  investigationSaveLoading.value[index] = true
  try {
    const investigationData = { ...investigation }
    delete investigationData.tempId
    delete investigationData.isNew
    
    if (investigation.isNew) {
      await emit('save-external-investigation', investigationData, -1) // -1 表示新增
    } else {
      await emit('save-external-investigation', investigationData, index)
    }
    
    // 保存成功后更新状态
    investigationChanged.value[index] = false
    if (investigation.isNew) {
      investigation.isNew = false
    }
  } finally {
    investigationSaveLoading.value[index] = false
  }
}

const deleteInvestigation = async (investigation, index) => {
  if (investigation.isNew) {
    // 新增的记录直接移除
    externalInvestigations.value.splice(index, 1)
    return
  }
  
  investigationDeleteLoading.value[index] = true
  try {
    await emit('delete-external-investigation', investigation, index)
    // 删除成功后从列表中移除
    externalInvestigations.value.splice(index, 1)
  } finally {
    investigationDeleteLoading.value[index] = false
  }
}

// =============== 数据更新方法（父组件调用） ===============
const updateExternalInvestigations = (newList) => {
  const processedList = newList.map(investigation => ({
    ...investigation,
    signatureDate: safeDateValue(investigation.signatureDate)
  }))
  externalInvestigations.value = cloneDeep(processedList)
  originalExternalInvestigations.value = cloneDeep(processedList)
}

// 获取编辑后的数据，用于保存到后端
const getEditedData = () => {
  // 直接返回externalInvestigations数组
  return externalInvestigations.value
}

defineExpose({
  updateExternalInvestigations,
  getEditedData
})
</script>